package net.xdclass.manager.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.xdclass.manager.TrafficManager;
import net.xdclass.mapper.TrafficMapper;
import net.xdclass.model.TrafficDO;
import net.xdclass.util.TimeUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author Allen
 * @version 1.0
 * @date 2022/12/7 11:43
 */
@Service
public class TrafficManagerImpl implements TrafficManager {
	@Resource
	private TrafficMapper trafficMapper;

	@Override
	public int add(TrafficDO trafficDO) {
		return trafficMapper.insert(trafficDO);
	}

	/**
	 * 分⻚查询可⽤的
	 *
	 * @param page
	 * @param size
	 * @param accountNo
	 * @return
	 */
	@Override
	public IPage<TrafficDO> pageAvailable(Integer page, Integer size, Long accountNo) {

		Page<TrafficDO> pageInfo = new Page<>(page, size);
		String today = TimeUtil.format(new Date(), "yyyy-MM-dd");

		Page<TrafficDO> trafficDOPage = trafficMapper
			.selectPage(pageInfo, new QueryWrapper<TrafficDO>()
			.eq("account_no", accountNo).ge("expired_date", today)
				.orderByDesc("gmt_create"));


//		LambdaQueryWrapper<TrafficDO> objectLambdaQueryWrapper = Wrappers.lambdaQuery();
		return trafficDOPage;
	}


	@Override
	public TrafficDO findByIdAndAccountNo(Long trafficId, Long accountNo) {
		TrafficDO trafficDO = trafficMapper.selectOne(new QueryWrapper<TrafficDO>()
			.eq("account_no", accountNo).eq("id", trafficId));
		return trafficDO;
	}

	/**
	 * 给某个流量包增加天使用次数
	 *
	 * @param currentTrafficId
	 * @param accountNo
	 * @param dayUsedTimes
	 * @return
	 */
	@Override
	public int addDayUsedTimes(Long currentTrafficId, Long accountNo, Integer dayUsedTimes) {
		return trafficMapper.update(null, new UpdateWrapper<TrafficDO>()
			.eq("account_no", accountNo)
			.eq("id", currentTrafficId).set("day_used", dayUsedTimes));
	}
}
